﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using MoneyBook.Web.Models;

namespace MoneyBook.Web.Services {

    [EnableClientAccess()]
    public class MembersService : LinqToEntitiesDomainService<MoneyBookEntities> {

        public IQueryable<Member> GetMembers() {
            return this.ObjectContext.Members.OrderBy(m => m.MemberId);
        }

        public void AddMember(Member member) {
            if (MemberExists(member.MemberName)) {
                //TODO : resource
                throw new ValidationException("指定されたメンバーは既に存在します。");
            }

            member.IsAdmin = false;
            member.PasswordHash = Authentication.GetPasswordHash(member.Password);

            ObjectContext.Members.AddObject(member);
        }

        private bool MemberExists(string memberName) {
            bool exists = false;
            using (MoneyBookEntities context = new MoneyBookEntities()) {
                exists = context.Members.Any(m => m.MemberName == memberName);
            }
            return exists;
        }


    }
}


